let web=""
let email=""
var isread=0;//等于0时，读邮件变已读  等于1时，不改变状态
$(document).ready(function () {
	$.ajax({
		url: 'email/selectWeb',
		type: 'GET',
		async: false, // 同步
		success: function (date) {
			web=date.data;
		}
	});
	CKEDITOR.config.readOnly = true;
	var emailID=getQueryString("email_id");
	var es = getQueryString("ids");
	$("#emailID").val(emailID);
	$("#emailids").val(es);
	isread=getQueryString("isread");
	GetEmailForID(emailID);

});
function reUploadEmail() {
	$.ajax({
		url: 'email/upLoadAdjunctOne2',
		type: 'GET',
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		async:false,
		data: {
			"emailID":getQueryString("email_id")
		},
		success: function (date) {
			getEmailAdjunct(email_id)
		},
		error:function (r) {

		}
	});
}
function forward(){
	layer.open({
		type: 2
		,title: "内部转发、分发"
		,area:  ['70%', '70%']
		,btn: ['确定', '取消']
		,shade: 0.8
		,btnAlign: 'c'
		,moveType: 1 //拖拽模式，0或者1
		,content: "views/jsp/BasicData/email/internalforwarding.jsp"
		,yes: function(index, layero){
			var res = window["layui-layer-iframe"+index].callbackdata();
			if(res.code==""||res.code==null){
				layer.msg("未选择收件人")
			}else{
				var code=res.code;
				var idea=res.idea;
				var emails=new Array()
				emails.push(email)
				var date={
					"code":code,
					"idea":idea,
					"emails":emails
				}
				$.ajax({
					url: 'email/emailForward',
					type: 'POST',
					contentType: "application/json; charset=utf-8",
					data: JSON.stringify(date),
					success: function (date) {
						layer.msg(date.data);
					},
				});
				layer.closeAll();
			}
		}
	});
}

layui.use(['dropdown'], function () {
    var dropdown=layui.dropdown;
    showRemove();
    //移动邮件设置
    function  showRemove() {//查看联系人
        $.ajax({
            url: 'email/selectBox',
            type: 'GET',
            success: function (date) {
                var boxs= date.data
                dropdown.suite("#emailMove", {
                    template: "#yidongMenu",
                    success: function ($dom) {
                        for(let i in boxs){
                            var name=boxs[i].box_name
                            var id=boxs[i].box_id
                            if(boxs[i].box_grade==0){//出示自定义箱和联系人箱？
                                $("#moveEmailPeople").append("<div class=\"menu-item\">\n" +
                                    "<a href=\"javascript:;\" lay-event=\"alreadysentbox\" onclick='moveEmailForBox(0,"+id+")'><span class=\"\">"+name+"</span></a></div>")
                            }
                            if(boxs[i].box_grade==1){//出示自定义箱和联系人箱？
                                $("#moveEmailBoxs").append("<div class=\"menu-item\">\n" +
                                    "<a href=\"javascript:;\" lay-event=\"alreadysentbox\" onclick='moveEmailForBox(1,"+id+")'><span class=\"\">"+name+"</span></a></div>")
                            }
                        }
                    }
                });

            }
        });
    }
});


function moveEmailForBox(grade,id) {
	var emailID=getQueryString("email_id");
	var emails=new Array();
	var email={
		"email_id":emailID
	}
	emails.push(email)
	$.ajax({
		url: 'email/moveEmailBox?box_id='+id,
		type: 'POST',
		contentType: "application/json; charset=utf-8",
		data: JSON.stringify(emails),
		success: function (date) {
		}
	});
}
function changeEmailsClass(emailClass) {

	var emailID=getQueryString("email_id");
	var emails=new Array();
	var email={
		"email_id":emailID
	}
	emails.push(email)
	$.ajax({
		url: 'email/changeEmailsClass?emailClass='+emailClass,
		type: 'POST',
		contentType: "application/json; charset=utf-8",
		data: JSON.stringify(emails),
		success: function (date) {
			layer.msg("移动成功")
		}
	});

}
//获取url中的id
function getQueryString(name) {
	var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
	var r = window.location.search.substr(1).match(reg);
	if (r != null) {
		return unescape(r[2]);
	}
	return null;
}


function GetEmailForID(emailID) {
	$.ajax({
		url: 'email/showEmailbyID',
		type: 'GET',
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		async:false,
		data: {
			"emailID":emailID,
			"isread":isread
		},
		success: function (date) {
			email=date.data;
			$("#subject").append("<span>"+date.data.subject+"</span></br>")
			if(date.data.email_class==3){
				$("#emailDate").append("</br><button onclick='caogao(2)'>点击进行编辑</button>")
			}
			var size=Math.round(date.data.emailSize/1024)+"kb"
			$('#emailDate').append("<div>发件人：<span>"+date.data.senderAddresser+"</span></div>")
			$('#emailDate').append("<div>收件人：<span>"+date.data.recipientAddress+"</span></div>")
			$('#emailDate').append("<div>抄送人: <span>"+date.data.copyAddress+"</span></div>")
			$('#emailDate').append("<div>时间: <span>"+date.data.recDate+"</span></div>")
			$('#emailDate').append("<div>大小: <span>"+size+"</span></div>")
			console.log("ready",date.data.readyStatue)
			if(date.data.readyStatue==0||date.data.readyStatue==2){//未下载附件的情况下，或下载错误的情况下，再下载一次
				downAdjunct(date.data.email_id)
			}else{
				getEmailAdjunct(date.data.email_id)
			}
			},
		error: function (r) {
			console.log(r);
		}
	});
}
function downAdjunct(email_id) {

	$.ajax({
		url: 'email/upLoadAdjunctOne',
		type: 'GET',
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		async:false,
		data: {
			"emailID":email_id
		},
		success: function (date) {
			getEmailAdjunct(email_id)
		},
		error:function (r) {

		}
	});
}
$("#statistical").on("click",function () {
	parent.intab("views/jsp/Money/tpl/statistics.jsp","统计")
});

function getEmailAdjunct(emailID) {
	$("documents").ready(()=>{
	$.ajax({
		url: 'email/showEmailAdjunctbyID',
		type: 'GET',
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		async: false, // 同步
		data: {
			"emailID":emailID
		},
		success: function (data) {

			//展示附件
			//差遍历及附件功能
			var index=1;
			let  tmphtml=""
			var adNum=0;
			for(let i in data.data){
					if(data.data[i].isAdunct==1){
						adNum++;
						// $("#adjuncts").append("<a href='"+data.data[i].adjunctAddress+"'>附件"+index+":"+data.data[i].adjunctName+"</a><br>");
						 $("#adjuncts").append("<div  class=\"item\"  title='"+data.data[i].adjunctName+"'><div><img alt=\"\" src=\"statics/img/"+adjunctClass(data.data[i].adjunctName)+".png\"></div><div style=\"padding:6px;\"><p><a> "+data.data[i].adjunctName+"</a></p><div></div>"
							+"\n"+"<a class=\"sk-btn\"  onclick='showAdjunct(\""+data.data[i].adjunctAddress+"\",\""+data.data[i].adjunctName+"\")'>查看</a>"+"<a class=\"sk-btn\" onclick='downloadAdjunct(\""+data.data[i].adjunctAddress+"\",\""+data.data[i].adjunctName+"\")'>下载</a>"+
							 "</div></div>")
					}

					if(data.data[i].isText==1){
						tmphtml=data.data[i].textAddress
						// $("#content").append(data.data[i].textAddress)
					}
			}
			if(adNum>2){
				$("#ipt").prepend("<div><button id='downloadall' onclick='zipDown()' class='layui-btn layui-btn-xs'>附件打包</button></div>")
			}
			//  ftp/downloadimg?pathname=
			// web+ftp/downloadimg?pathname=
			// let str1="ftp/downloadimg?pathname=",str2=web+"ftp/downloadimg?pathname="
			// tmphtml=tmphtml.replace(/ftp\/downloadimg\?pathname\=+/g,str2)
			// console.log(tmphtml)
			// $("#content").html(tmphtml)
			// console.log("web",web)
			// document.getElementById("textarea").innerHTML=tmphtml
			$("#content").html(tmphtml)
			},

			// $("#content").html(tmphtml)

		error: function (r) {
			alert('Error! Please try again.' + r.responseText);
			console.log(r);
		}
	});
	})

}
function zipDown() {
	$.ajax({
		url: 'email/zipDown?email_id='+email.email_id,
		type: 'GET',
		async: false, // 同步
		success: function (data) {
			if(data.data[0]!=null){
				downLoad(data.data[0]+"/"+data.data[1],data.data[1])
			}
		},
	});
}

function adjunctClass(fileName) {
	var ff=fileName.split(".");
	var f1=ff[ff.length-1];
	return f1;
}
function  downloadAdjunct(path,filename) {
	debugger
	if(path==null){
		layer.msg("此文件不存在，请联系管理员");
		return;
	}

	var p=path.split("pathname=")
	var filePath=p[1].split("&filename=")[0]+p[1].split("&filename=")[1]
	downLoad(filePath,filename)
}
function downLoad(filePath,filename) {
	let xmlHttpRequest = new XMLHttpRequest();
	let url = "wjinfo/downloadfile2?filename=" + filePath;
	xmlHttpRequest.open('GET', url, true);
	//设置请求头
	xmlHttpRequest.setRequestHeader("Content-type", "application/json")
	xmlHttpRequest.responseType = "blob";
	xmlHttpRequest.send(null);
	xmlHttpRequest.onload = function() {
		let content = xmlHttpRequest.response;
		// 组装a标签
		let elink = document.createElement("a");

		//设置文件下载路径
		elink.download = decodeURIComponent(filename);
		elink.style.display = "none";
		let blob = new Blob([content], { type: 'application/force-download' });

		//解决下载不存在文件的问题，根据blob大小判断
		if(blob.size==0){
			layer.msg('服务器没找到此文件，请联系管理员!');
		}else{
			elink.href = window.URL.createObjectURL(blob);
			document.body.appendChild(elink);
			elink.click();
			document.body.removeChild(elink);
		}
	}
}
function  showAdjunct(path,filename) {
	debugger
	//path= ftp/downloadimg?pathname=/data0/AllPath/email/lynn@fengqish.com/1634980284/&filename=2021111122583084934
	//实际需要的path = /data0/AllPath/upload/WLCCB01/RKB100/warehouse/transfer/1636336320282.pdf
	var strings = path.split("tp/downloadimg?pathname=")[1].split("&filename=");
	path=strings[0]+strings[1]
	var fileExtension = filename.split('.').pop().toLowerCase();
	onLineonLineEmail(path,strings[1]+"."+fileExtension)
}

//在线预览，入参：附件在表中存放的路径
function onLineonLineEmail(url,filen) {
	// var url=data.path;
	$.ajax({
		url: 'ftp/onLineonLineEmail?pathString='+url+'&filename='+filen,
		type: 'GET',
		async: false, // 同步
		success: function (data) {
			openWindowLook(data.data);
		},
	});
}
function getUpOrDownEmail(UpOrDown) {
	var emailID1 = $("#emailID").val();
	var es=$("#emailids").val();
	var emailids = es.split(",");
	var index=0;
	if(UpOrDown=="up"){
		index=-1;
	}else if(UpOrDown=="down"){
		index=1;
	}
	for(i=0;i<emailids.length;i++){
		if(emailids[i]==emailID1){
			index=i+index;
			emailID1=emailids[index];
			break;
		}
	}
	if(index<0){
		alert("已到本页第一封")
	}else if(index==emailids.length-1){
		alert("已到本页最后一封")
	}else{
		$("#subject").empty();
		$('#emailDate').empty();
		$('#content').empty();
		getEmailAdjunct(emailID1);
		GetEmailForID(emailID1);
		$("#emailID").val(emailID1);
	}

}

//回复单人，type=0简单回复，1带全文回复，2带附件文回复
function answer(type) {
	var emailID=$("#emailID").val();
	window.location.href="views/jsp/BasicData/email/write.jsp?answer="+type+"&emailID="+emailID;
}

//全部回复 type=0简单回复，1带全文回复，2带附件文回复
function allanswer(type) {
	var emailID=$("#emailID").val();
	window.location.href="views/jsp/BasicData/email/write.jsp?Allanswer="+type+"&emailID="+emailID;
}

function relay(type) {
	var emailID=$("#emailID").val();
	window.location.href="views/jsp/BasicData/email/write.jsp?relay="+type+"&emailID="+emailID;
}

function caogao(type) {
	var emailID=$("#emailID").val();
	window.location.href="views/jsp/BasicData/email/write.jsp?caogao="+type+"&emailID="+emailID;
}

function deleteEmail() {
	var emailID=$("#emailID").val();
	var emails=new Array()
	var email={
		"email_id":emailID
	}
	emails.push(email)
	$.ajax({
		url: 'email/changeEmailsClass?emailClass=7',
		type: 'POST',
		contentType: "application/json; charset=utf-8",
		data: JSON.stringify(emails),
		success: function (date) {
			alert("删除成功")
		}
	});
}